package io.renren.modules.mark.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.mark.constant.DatasetConstant;
import io.renren.modules.mark.dao.MarkDatasetDao;
import io.renren.modules.mark.entity.MarkDatasetEntity;
import io.renren.modules.mark.entity.MarkItemEntity;
import io.renren.modules.mark.entity.MarkTeamUserEntity;
import io.renren.modules.mark.service.MarkDatasetService;
import io.renren.modules.mark.service.MarkItemService;
import io.renren.modules.mark.service.MarkTeamUserService;
import io.renren.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author
 * @email
 * @date
 */
@RestController
@RequestMapping("mark/markdataset")
@Api(value = "DatasetApi", description = "任务增删改查", tags = {"任务接口"})
public class MarkDatasetController extends AbstractController {
    @Autowired
    private MarkDatasetService markDatasetService;

    @Autowired
    private MarkItemService markItemService;

    @Autowired
    private MarkTeamUserService markTeamUserService;

    @Autowired
    private MarkDatasetDao markDatasetDao;

    /**
     * 查询标注员的任务
     */
    @GetMapping("/listDataset")
    @ApiOperation("根据用户id查询拥有的任务")
    public R listDataset(){
        Long userId = getUserId();
        //根据用户ID查询拥有的任务
        QueryWrapper<MarkItemEntity> qw = new QueryWrapper<>();
        if(userId!=Constant.SUPER_ADMIN && userId!=Constant.ADMIN){
            qw.select("distinct dataset_id").eq("user_id",userId);
        }else{
            qw.select("distinct dataset_id");
        }
        List<MarkItemEntity> list = markItemService.list(qw);
        List<Integer> collect = list.stream().map(MarkItemEntity::getDatasetId).collect(Collectors.toList());
        //查询任务详情信息，状态1 时间倒序
        QueryWrapper<MarkDatasetEntity> queryWrapper = new QueryWrapper<>();
        if(collect.size()==0){
            return R.ok().put("list",null);
        }
        queryWrapper
                .orderByDesc("create_time")
                .in("dataset_id",collect);
        return R.ok().put("list", markDatasetDao.selectList(queryWrapper));
    }

    /**
     * 查询审批任务列表
     */
    @GetMapping("/listApproveDataset")
    @ApiOperation("查询审核员/管理员的任务列表")
    public R listByUserId() {
        Long userId = getUserId();
        QueryWrapper<MarkDatasetEntity> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        if (userId != Constant.SUPER_ADMIN && userId != Constant.ADMIN) { //管理员可以查看所有的任务,审核员根据团队查询任务，标注员根据图片查询任务
            QueryWrapper<MarkTeamUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("team_id").eq("user_id", userId);
            List<MarkTeamUserEntity> list = markTeamUserService.list(queryWrapper);
            List<Integer> collect = list.stream().map(MarkTeamUserEntity::getTeamId).collect(Collectors.toList());
            if(collect.size() > 0) qw.in("team_id", collect);
            else return R.ok().put("list",collect);
        }
        List<MarkDatasetEntity> listRel = markDatasetService.list(qw);
        return R.ok().put("list", listRel);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("列表查询")
    @RequiresPermissions("mark:markdataset:list")
    public R list(@RequestParam Map<String, Object> params) {
        Long userId = getUserId();
        if(userId!= Constant.SUPER_ADMIN && userId!= Constant.ADMIN){
            params.put("createUserid",getUserId());
        }
        PageUtils page = markDatasetService.queryPage(params);

        return R.ok().put("page", page);
    }

    @PostMapping("submit")
    @RequiresPermissions("mark:markdataset:save")
    public R submit(@RequestBody Integer datasetId) {
        if (datasetId == null) {
            throw new RRException("请选择任务");
        }
        markDatasetService.submit(datasetId);
        return R.ok();
    }

    @GetMapping("getType")
    @ApiOperation("获取任务类型")
    public R getType() {
        R r = R.ok();
        Map<Integer, String> map = DatasetConstant.TYPELIST;
        List list = new ArrayList();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            Map map1 = new HashMap();
            map1.put("key", entry.getKey());
            map1.put("value", entry.getValue());
            list.add(map1);
        }
        r.put("list", list);
        return r;
    }

    /**
     * 信息
     */
    @GetMapping("/info/{datasetId}")
    @ApiOperation("根据id查询任务")
    //@RequiresPermissions("mark:markdataset:info")
    public R info(@PathVariable("datasetId") Integer datasetId) {
        MarkDatasetEntity markDataset = markDatasetService.getById(datasetId);

        return R.ok().put("markDataset", markDataset);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("保存")
    @RequiresPermissions("mark:markdataset:save")
    public R save(@RequestBody MarkDatasetEntity markDataset) {
        markDataset.setCreateTime(new Date());
        markDataset.setState(0);
        markDataset.setTotal(0);
        markDataset.setIsDelete(0);
        markDataset.setCreateUserid(getUserId());
        try{
            markDatasetService.save(markDataset);
        }catch (Exception dk){
            if(dk.getMessage().contains("name_UNIQUE")){
                throw new RRException("任务名称已存在");
            }else {
                throw new RRException("保存任务失败,请检查任务名称是否过长");
            }
        }

        return R.ok().put("datasetId",markDataset.getDatasetId());
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("更新update")
    @RequiresPermissions("mark:markdataset:save")
    public R update(@RequestBody MarkDatasetEntity markDataset) {
        try{
            markDatasetService.updateById(markDataset);
        }catch (Exception dk){
            if(dk.getMessage().contains("mark_team.name_UNIQUE")){
                throw new RRException("任务名称已存在");
            }else {
                throw new RRException("更新任务失败,请检查任务名称是否过长");
            }
        }

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation("删除")
    @RequiresPermissions("mark:markdataset:delete")
    public R delete(@RequestBody Integer[] datasetIds) {
        markDatasetService.removeByIds(Arrays.asList(datasetIds));

        return R.ok();
    }

}
